package com.lihaozhe.paymentservice.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 支付服务控制器
 * 模拟支付处理流程
 *
 * @author 李昊哲
 * @version 1.0.0
 */
@RestController
@RequestMapping("/api/payments")
public class PaymentController {

  // 支付记录存储
  private final Map<String, Map<String, Object>> payments = new ConcurrentHashMap<>();
  private final AtomicLong paymentIdCounter = new AtomicLong(1000);

  @Value("${server.port}")
  private String serverPort;

  /**
   * 创建支付
   * POST /api/payments
   */
  @PostMapping
  public Map<String, Object> createPayment(@RequestBody Map<String, Object> paymentRequest) {
    Long orderId = Long.valueOf(paymentRequest.get("orderId").toString());
    Double amount = Double.valueOf(paymentRequest.get("amount").toString());
    Long userId = Long.valueOf(paymentRequest.get("userId").toString());

    System.out.println("处理支付请求 - 订单ID: " + orderId + ", 金额: " + amount + ", 用户ID: " + userId);

    // 模拟支付处理
    try {
      // 模拟支付处理时间
      Thread.sleep(200);

      // 生成支付ID
      String paymentId = "PAY_" + paymentIdCounter.incrementAndGet();

      // 模拟支付成功（90%成功率）
      boolean success = Math.random() > 0.1;
      String status = success ? "SUCCESS" : "FAILED";

      // 保存支付记录
      Map<String, Object> payment = Map.of(
          "paymentId", paymentId,
          "orderId", orderId,
          "amount", amount,
          "userId", userId,
          "status", status,
          "paymentTime", System.currentTimeMillis(),
          "processedBy", "payment-service:" + serverPort
      );

      payments.put(paymentId, payment);

      return Map.of(
          "success", success,
          "paymentId", paymentId,
          "status", status,
          "message", success ? "支付成功" : "支付失败，请重试",
          "processedBy", "payment-service:" + serverPort
      );

    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      return Map.of(
          "success", false,
          "paymentId", null,
          "status", "FAILED",
          "message", "支付处理被中断"
      );
    } catch (Exception e) {
      return Map.of(
          "success", false,
          "paymentId", null,
          "status", "FAILED",
          "message", "支付处理异常: " + e.getMessage()
      );
    }
  }

  /**
   * 查询支付状态
   * POST /api/payments/{paymentId}/status
   */
  @PostMapping("/{paymentId}/status")
  public Map<String, Object> getPaymentStatus(@RequestBody Map<String, Object> request) {
    String paymentId = request.get("paymentId").toString();

    Map<String, Object> payment = payments.get(paymentId);
    if (payment == null) {
      return Map.of(
          "status", "NOT_FOUND",
          "message", "支付记录不存在",
          "paymentId", paymentId
      );
    }

    return Map.of(
        "status", payment.get("status"),
        "paymentId", paymentId,
        "orderId", payment.get("orderId"),
        "amount", payment.get("amount"),
        "paymentTime", payment.get("paymentTime"),
        "processedBy", payment.get("processedBy")
    );
  }

  /**
   * 退款处理
   * POST /api/payments/refund
   */
  @PostMapping("/refund")
  public Map<String, Object> refund(@RequestBody Map<String, Object> refundRequest) {
    String paymentId = refundRequest.get("paymentId").toString();
    Double refundAmount = Double.valueOf(refundRequest.get("amount").toString());

    System.out.println("处理退款请求 - 支付ID: " + paymentId + ", 退款金额: " + refundAmount);

    // 模拟退款处理
    try {
      Thread.sleep(150);

      Map<String, Object> payment = payments.get(paymentId);
      if (payment == null) {
        return Map.of(
            "success", false,
            "message", "原支付记录不存在",
            "refundId", null
        );
      }

      // 生成退款ID
      String refundId = "REFUND_" + System.currentTimeMillis();

      return Map.of(
          "success", true,
          "refundId", refundId,
          "paymentId", paymentId,
          "refundAmount", refundAmount,
          "message", "退款处理成功",
          "processedBy", "payment-service:" + serverPort
      );

    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      return Map.of(
          "success", false,
          "message", "退款处理被中断"
      );
    }
  }

  /**
   * 获取所有支付记录（管理用）
   * GET /api/payments/all
   */
  @GetMapping("/all")
  public Map<String, Object> getAllPayments() {
    return Map.of(
        "totalPayments", payments.size(),
        "payments", payments.values(),
        "service", "payment-service:" + serverPort
    );
  }

  /**
   * 健康检查
   * GET /api/payments/health
   */
  @GetMapping("/health")
  public Map<String, Object> health() {
    return Map.of(
        "status", "UP",
        "service", "payment-service",
        "port", serverPort,
        "timestamp", System.currentTimeMillis(),
        "totalPayments", payments.size()
    );
  }
}
